package cn.elead.chaos.sso.server.web.system.controller;

import java.io.File;
import java.io.IOException;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import cn.elead.chaos.core.enums.BusinessType;
import cn.elead.chaos.framework.file.FileUploadUtils;
import cn.elead.chaos.framework.monitor.operlog.Log;
import cn.elead.chaos.framework.properties.ChaosProperties;
import cn.elead.chaos.framework.web.global.ApiAssert;
import cn.elead.chaos.framework.web.global.ErrorCodeEnum;
import cn.elead.chaos.framework.web.global.response.UnifiedReturn;
import cn.elead.chaos.mybatils.web.controller.BaseController;
import cn.elead.chaos.sso.core.util.SsoUtils;
import cn.elead.chaos.sso.server.utli.Current;
import cn.elead.chaos.sso.server.web.login.service.RedisSaveService;
import cn.elead.chaos.sso.server.web.system.domain.SysUser;
import cn.elead.chaos.sso.server.web.system.service.ISysUserService;
import cn.elead.chaos.sso.server.web.system.service.impl.SysPasswordService;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;

/**
 * 个人信息 业务处理
 * 
 * @author ruoyi
 */
@Slf4j
@Controller
@RequestMapping("/system/user/profile")
public class SysProfileController extends BaseController {

	private String prefix = "system/user/profile";

	@Autowired
	private ISysUserService userService;

	@Autowired
	private SysPasswordService sysPasswordService;

	@Autowired
	private RedisSaveService redisSaveService;

	@Autowired
	private ChaosProperties chaos;

	/**
	 * 个人信息
	 */
	@GetMapping()
	public String profile(ModelMap mmap) {
		SysUser user = userService.selectUserById(Current.getUserId());
		mmap.put("user", user);
		mmap.put("roleGroup", userService.selectUserRoleGroup(user.getUserId()));
		mmap.put("postGroup", userService.selectUserPostGroup(user.getUserId()));
		return prefix + "/profile";
	}

	/**
	 * 个人信息
	 */
	@ResponseBody
	@GetMapping("crurrent")
	public SysUser crurrent() {
		SysUser sysUser = Current.getUser();
		if (ObjectUtil.isNotEmpty(sysUser)) {
			sysUser.setPassword("");
			sysUser.setSalt("");
			// http://localhost:8080/sso/profile/avatar/20200118120528/abc6260b20fde727a8f7a00739d32063.png
			String resourcePath = chaos.getPath().getResourcePath();
			String avatar = chaos.getPath().getPrefix().getAvatar();
			sysUser.setAvatar(chaos.getHost() + resourcePath + avatar + sysUser.getAvatar());
		}
		return sysUser;
	}

	@ResponseBody
	@UnifiedReturn
	@GetMapping("/checkPassword")
	public boolean checkPassword(String password) {
		SysUser user = userService.selectUserById(Current.getUserId());
		if (sysPasswordService.matches(user, password)) {
			return true;
		}
		return false;
	}

	@GetMapping("/resetPwd")
	public String resetPwd(ModelMap mmap) {
		mmap.put("user", userService.selectUserById(Current.getUserId()));
		return prefix + "/resetPwd";
	}

	@ResponseBody
	@PostMapping("/resetPwd")
	@Log(title = "重置密码", businessType = BusinessType.UPDATE)
	public void resetPwd(String oldPassword, String newPassword) {

		SysUser user = Current.getUser();
		if (StrUtil.isNotEmpty(newPassword) && sysPasswordService.matches(user, oldPassword)) {
			user.setPassword(sysPasswordService.encryptPassword(newPassword));
			if (userService.resetUserPwd(user) > 0) {
				Current.bind(user);
				redisSaveService.saveSysUserToRedis(user.getUserId(), user);
			}
		} else {
			ApiAssert.failure(ErrorCodeEnum.INTERNAL_SERVER_ERROR.convert("修改密码失败，旧密码错误"));
		}

	}

	/**
	 * 修改用户
	 */
	@GetMapping("/edit")
	public String edit(ModelMap mmap) {
		mmap.put("user", userService.selectUserById(SsoUtils.getUserId()));
		return prefix + "/edit";
	}

	/**
	 * 修改头像
	 */
	@GetMapping("/avatar")
	public String avatar(ModelMap mmap) {
		mmap.put("user", userService.selectUserById(SsoUtils.getUserId()));
		return prefix + "/avatar";
	}

	/**
	 * 修改用户
	 */
	@ResponseBody
	@PostMapping("/update")
	@Log(title = "个人信息", businessType = BusinessType.UPDATE)
	public void update(SysUser user) {
		SysUser currentUser = userService.selectUserById(SsoUtils.getUserId());
		currentUser.setUserName(user.getUserName());
		currentUser.setEmail(user.getEmail());
		currentUser.setPhonenumber(user.getPhonenumber());
		currentUser.setSex(user.getSex());
		userService.updateUserInfo(currentUser);
	}

	/**
	 * 保存头像
	 * 
	 * @throws IOException
	 */
	@ResponseBody
	@PostMapping("/updateAvatar")
	@Log(title = "个人信息", businessType = BusinessType.UPDATE)
	public void updateAvatar(@RequestParam("avatarfile") MultipartFile file) throws IOException {
		SysUser currentUser = userService.selectUserById(SsoUtils.getUserId());
		if (!file.isEmpty()) {
			String avatar = upload(file);
			// String avatar = FileUploadUtils.upload(Chaos.getAvatarUploadPath(), file);
			currentUser.setAvatar(avatar);
			userService.updateUserInfo(currentUser);

		}
	}

	/**
	 * 上传头像
	 * 
	 * @param file
	 * @return
	 */
	@ApiOperation("上传头像")
	private String upload(MultipartFile file) {
		String suffix = FileUploadUtils.getExtension(file);
		try {
			String avatarPath = chaos.getPath().getPrefix().getAvatar();
			String dir = StrUtil.addSuffixIfNot(chaos.getPath().getFilePath() + avatarPath + "profile", "/");
			File upload = new File(dir);
			if (!upload.exists()) {
				upload.mkdirs();
			}
			String avatarId = SsoUtils.getUserId();
			String filePath = dir + avatarId + "." + suffix;
			String resourcePrefix = chaos.getPath().getResourcePrefix();
			// 存入硬盘
			File dest = new File(filePath);
			file.transferTo(dest);
			// http://localhost:8080/sso/static/avatar/profile/admin.png
			return StrUtil.addSuffixIfNot(chaos.getHost() + resourcePrefix + avatarPath + "profile", "/") + avatarId + "." + suffix;
		} catch (IllegalStateException | IOException e) {
			log.error("上传失败");
		}
		return null;
	}

}